<template>
  <div>
    <h2>课程文章管理</h2>
    <p>当前课程ID：{{ courseId }}</p>
    <el-button type="primary" @click="openAddDialog" style="margin-bottom: 16px;">新增博客</el-button>
    <el-table :data="blogList" border style="width: 100%">
      <el-table-column prop="title" label="博客标题" />
      <el-table-column prop="content" label="博客内容" show-overflow-tooltip />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.blogId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="90vw" style="max-width:1200px;">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入博客标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <VMdEditor v-model="form.content" height="600px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  addBlogService,
  updateBlogService,
  deleteBlogService,
  getBlogDetailService,
  getBlogListByCourseService
} from '@/apis/blog'
// 引入Markdown编辑器
import VMdEditor from '@kangc/v-md-editor/lib/codemirror-editor'
import '@kangc/v-md-editor/lib/style/codemirror-editor.css'
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js'
import '@kangc/v-md-editor/lib/theme/style/github.css'
import Prism from 'prismjs'

// 关键：引入 codemirror 及其样式（v5版本才有lib/codemirror.css）
import Codemirror from 'codemirror'
import 'codemirror/lib/codemirror.css'
// 滚动条插件
import 'codemirror/addon/scroll/simplescrollbars.js'
import 'codemirror/addon/scroll/simplescrollbars.css'

// 关键：配置 Codemirror
VMdEditor.Codemirror = Codemirror

VMdEditor.use(githubTheme, { Prism })

const route = useRoute()
const courseId = route.params.courseId
const blogList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增博客')
const formRef = ref(null)
const form = ref({
  blogId: null,
  title: '',
  content: ''
})
const rules = {
  title: [{ required: true, message: '请输入博客标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入博客内容', trigger: 'blur' }]
}

// 获取博客列表
const getBlogList = async () => {
  try {
    const res = await getBlogListByCourseService(courseId)
    if (res.code === 1000) {
      blogList.value = res.data.map(item => ({
        ...item,
        blogId: item.blogId || item.id // 兼容后端返回id
      }))
    }
  } catch (e) {
    ElMessage.error('获取博客列表失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增博客'
  form.value = {
    blogId: null,
    title: '',
    content: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  dialogTitle.value = '编辑博客'
  try {
    const res = await getBlogDetailService(row.blogId)
    if (res.code === 1000) {
      form.value = {
        blogId: res.data.blogId,
        title: res.data.title,
        content: res.data.content
      }
      dialogVisible.value = true
    }
  } catch (e) {
    ElMessage.error('获取博客详情失败')
  }
}

// 删除博客
const handleDelete = (blogId) => {
  console.log('删除博客ID:', blogId)
  ElMessageBox.confirm('确认删除该博客吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteBlogService(blogId)
      if (res.code === 1000) {
        ElMessage.success('删除成功')
        getBlogList()
      }
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.value.blogId) {
          res = await updateBlogService({
            blogId: form.value.blogId,
            title: form.value.title,
            content: form.value.content
          })
        } else {
          res = await addBlogService({
            courseId,
            title: form.value.title,
            content: form.value.content
          })
        }
        if (res.code === 1000) {
          ElMessage.success(form.value.blogId ? '更新成功' : '新增成功')
          dialogVisible.value = false
          getBlogList()
        }
      } catch (e) {
        ElMessage.error(form.value.blogId ? '更新失败' : '新增失败')
      }
    }
  })
}

onMounted(() => {
  getBlogList()
})
</script> 